package com.niit.dao.impl;

import java.util.List;

import com.niit.bean.Note;
import com.niit.bean.User;
import com.niit.dao.NoteDao;
import com.niit.utils.DbUtil;

public class NoteDaoImpl implements NoteDao {

	private DbUtil util =new DbUtil();
	@Override
	public int add(Note t) {
		String sql = "insert into tb_note (repoId,title,content) values (?,?,?)";
		int a = util.update(sql,t.getRepoId(),t.getTitle(),t.getContent());
		return a;
	}

	@Override
	public int delete(Note t) {
		String sql="delete from tb_note where id=? ";
		int a=util.update(sql, t.getId());
		return a;
	}

	@Override
	public int update(Note t) {
		String sql="update tb_note set repoId=?,title=?,content=? where id=?";
		int a=util.update(sql, t.getRepoId(),t.getTitle(),t.getContent(),t.getId());
		return a;
	}

	@Override
	public List<Note> findAll(int start, int end) {
		String sql="select * from(select rownum r,tb_note.* from tb_note) a where a.r>? and a.r<=?";
		List<Note> list =util.select(sql, Note.class, start,end);
		return list;
	}

	@Override
	public int findTotal(User user,String repoId) {
		String sql = null;
		if(repoId==null||"".equals(repoId)){
			sql = "select count(*) from tb_note o,tb_note_repo r where o.repoid=r.repoid and r.username = '"+user.getUsername()+"'";
		}else{
			sql = "select count(*) from tb_note o,tb_note_repo r where o.repoid="+repoId+" and o.repoid=r.repoid and r.username = '"+user.getUsername()+"'";
		}
		int count = util.selectCount(sql);
		return count;
	}

	@Override
	public List<Note> findNotes(User user, String repoId, int start, int end) {
		String sql = null;
		if(repoId!=null&&!"".equals(repoId)){
			sql = "select * from(select rownum r,o.* from tb_note o,tb_note_repo r where o.repoid=r.repoid and r.repoid="+repoId+" and r.username='"+user.getUsername()+"') a where a.r>"+start+" and a.r<="+end+"";
			return util.select(sql, Note.class);
		}else{
			sql = "select * from(select rownum r,o.* from tb_note o,tb_note_repo r where o.repoid=r.repoid and r.username='"+user.getUsername()+"') a where a.r>"+start+" and a.r<="+end+"";
			return util.select(sql, Note.class);
		}
		
	}

	@Override
	public int findTotal() {
		String sql = "select count(*) from tb_note";
		return util.selectCount(sql);
	}

	@Override
	public Note findNoteById(String id) {
		String sql = "select * from tb_note where id=?";
		List<Note> list =  util.select(sql, Note.class, id);
		return list.size()==0?null:list.get(0);
	}

	@Override
	public int getSeqNextVal() {
		String sql = "select max(id) from tb_note";
		return util.selectCount(sql);
	}
}
